import React from 'react'
import { connect } from 'dva'
import moment from 'moment'
import Upload from '@/components/Upload'
import { Form, Row, Col, Input, Select, DatePicker, Popconfirm, Popover, Button, List, message } from 'antd'
import styles from './BaseInfo.less'

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select

@connect(({ user, projectHall, loading }) => ({
  user,
  projectHall,
  loading: loading.effects['projectHall/fetchProject'],
}))
class TimeRelatedForm extends React.Component {
  state = {
    department: '',
    staff: '',
    time: [],
    start: Date.now(),
    end: Date.now(),

    name: 'file',
    action: '/project/Upload/uploadFile',
    headers: {},
    multiple: true
  }

  componentDidMount() {
    const token = window.localStorage.getItem('token') || ''
    this.setState({
      headers: { Authorization: `Bearer ${token}`, }
    })
  }

  handleSubmit = e => {
    e.preventDefault()

    const { form, dispatch } = this.props

    form.validateFields((err, fieldsValue) => {
      if (err) {
        return
      }
      const { time, keys, projectId, projectName, file } = fieldsValue
      if (file[0]) {
        dispatch({
          type: 'projectHall/handleSubmit',
          payload: {
            project_id: projectId,
            name: projectName,
            start: time[0].unix() * 1000,
            end: time[1].unix() * 1000,
            task: keys,
            file
          }
        })
      } else {
        message.error('上传文件为必选项')
      }
    })

  }

  uploadFile = ({ file = {} }) => {
    const { dispatch, projectHall } = this.props
    const { profile = {} } = projectHall
    const { status, data = [] } = file.response || {}
    if (file.status === 'done' && status) {
      const normalizeFile = profile.file || []

      dispatch({
        type: 'projectHall/save',
        payload: {
          profile: {
            ...profile,
            file: [...normalizeFile, {
              name: file.name,
              url: data.splice(data.length - 1, 1)[0]
            }],
          }
        }
      })

      message.success(`${file.name} 文件上传成功`)
    } else if (file.status === 'error') {
      message.error(`${file.name} 文件上传失败，${data}`)
    }
  }

  changeFile = (index, { file = {} }) => {
    const { dispatch, projectHall } = this.props
    const { profile = {} } = projectHall
    const { status, data = [] } = file.response || {}
    if (file.status === 'done' && status) {
      const normalizeFile = profile.file || []
      normalizeFile.splice(index, 1, { name: file.name, url: data[0] })
      dispatch({
        type: 'projectHall/save',
        payload: {
          profile: {
            ...profile,
            file: [...normalizeFile],
          }
        }
      })
      message.success(`${file.name} 文件替换成功，还需要提交`)
    } else if (file.status === 'error') {
      message.error(`${file.name} 文件替换失败.`)
    }
  }

  deleteFile = index => {
    const { dispatch, projectHall } = this.props
    const { profile = {} } = projectHall
    const { file = {} } = profile
    if (Array.isArray(file)) {
      file.splice(index, 1)
      dispatch({
        type: 'projectHall/save',
        payload: {
          profile: {
            ...profile,
            file,
          }
        }
      })
    }
  }

  // 删除人员&&新增
  // eslint-disable-next-line
  removeStaff = (index, task_id) => {
    const { form, dispatch } = this.props
    const { getFieldValue } = form
    const keys = getFieldValue('keys')
    // eslint-disable-next-line
    if ((index === 0 && task_id) || (index && task_id)) {
      keys.splice(index, 1)
      form.setFieldsValue({ keys })
      dispatch({
        type: 'projectHall/removeStaff',
        payload: { task_id }
      })
    } else {
      message.error('这是个 bug，请刷新后再试一试')
    }
  }

  // 二级联动&&新增
  queryStaff = (flag, value) => {
    const { dispatch, user } = this.props
    const { department = [], staff = [] } = user

    const addObj = {}
    switch (flag) {
      case 0:
        dispatch({ type: 'user/fetchStaff', payload: { department_id: value } })
        // eslint-disable-next-line
        const departmentArray = department.filter(it => {
          if (it.department_id === value) return true
          return false
        })
        // eslint-disable-next-line
        const departmentName = departmentArray[0] ? departmentArray[0].department_name : ''
        Object.assign(addObj, { department: value, department_name: departmentName })
        break
      case 1:
        // eslint-disable-next-line
        const staffArray = staff.filter(it => {
          if (it.staff_id === value) return true
          return false
        })
        // eslint-disable-next-line
        const staffName = staffArray[0] ? staffArray[0].staff_name : ''
        Object.assign(addObj, { staff: value, staff_name: staffName })
        break
      case 2:
        Object.assign(addObj, { start: value[0].unix() * 1000, end: value[1].unix() * 1000 })
        break
      default:
        break
    }
    this.setState(state => ({
      ...state,
      ...addObj
    }))
  }

  postStaff = () => {
    const { form, dispatch, projectHall } = this.props
    const { profile = {} } = projectHall

    // eslint-disable-next-line
    const { department, department_name, staff, staff_name, time, start, end } = this.state

    if (department && staff) {
      // eslint-disable-next-line
      const keys = form.getFieldValue('keys')
      const nextKeys = keys.concat([{ department, department_name, staff, staff_name, time, start, end }])
      const planTime = form.getFieldValue('time')
      const planstarttime = planTime[0].unix() * 1000
      if (start < planstarttime) {
        message.error('员工项目开始时间应 >= 项目计划开始时间')
      } else if (start >= end) {
        message.error('员工项目结束时间应大于开始时间')
      } else {
        form.setFieldsValue({ keys: nextKeys })
        dispatch({
          type: 'projectHall/postStaff',
          payload: {
            project: profile.project_id,
            staff,
            department,
            start: moment(start).format('YYYY-MM-DD HH:mm:ss'),
            end: moment(end).format('YYYY-MM-DD HH:mm:ss')
          }
        })
      }
    } else {
      message.error('请选择部门及员工')
    }

  }

  render() {
    const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 } } }

    const { action, headers, multiple } = this.state
    // eslint-disable-next-line
    const uploadProps = { name: this.state.name, action, headers, multiple }
    const { form, user, projectHall } = this.props
    const { getFieldDecorator, getFieldValue } = form
    const { department = [], staff = [] } = user
    const { profile } = projectHall
    // eslint-disable-next-line
    let { name = '', task = null, file = [] } = profile
    let initial = {}

    if (task) {
      initial = { initialValue: [moment(profile.start * 1000), moment(profile.end * 1000)] }
      task = task.map(item => {
        const departmentArray = department.filter(it => {
          if (it.department_id === item.department) return true
          return false
        })
        return {
          task_id: item.task_id,
          department: item.department,
          staff: item.staff,
          start: item.start * 1000,
          end: item.end * 1000,

          // 扩展
          department_name: departmentArray[0].department_name,
          staff_name: item.staff_name
        }
      })
    }

    getFieldDecorator('keys', { initialValue: task || [] })
    const keys = getFieldValue('keys')

    return (
      <Form onSubmit={this.handleSubmit}>
        {getFieldDecorator('projectId', {initialValue: profile.project_id || 0})(<Input type='hidden' />)}
        {getFieldDecorator('file', {initialValue: profile.file || []})(<Input type='hidden' />)}
        
        <FormItem {...formItemLayout} label="项目名称">
          {getFieldDecorator('projectName', {
            initialValue: name,
            rules: [{ type: 'string', required: true, message: '请填写项目名称' }],
          })(<Input style={{ width: 335 }} placeholder="请填写项目名称" />)}
        </FormItem>
        
        <FormItem {...formItemLayout} label="项目周期">
          {getFieldDecorator('time', {
            ...initial,
            rules: [{ type: 'array', required: true, message: '请选择项目开始、结束时间' }],
          })(<RangePicker />)}
        </FormItem>

        {
          profile.project_id 
          &&
          <List
            header={<section>项目参与人员及周期安排</section>}
            bordered
            dataSource={keys}
            size="small"
            style={{ width: 749, marginLeft: 120, marginBottom: 36, overflow: 'hidden' }}
            renderItem={(item, index) => (
              <List.Item key={item.department_id} className='fadeInRight animated'>
                <section className={styles.addProjectMem}>
                  <span style={{width: '22%'}}>{item.department_name}</span>
                  <span style={{width: '22%'}}>{item.staff_name}</span>
                  <span style={{width: '22%'}}>{Number(item.start) && moment(item.start).format('YYYY-MM-DD HH:mm:ss')}</span>
                  <span style={{width: '22%'}}>{Number(item.end) && moment(item.end).format('YYYY-MM-DD HH:mm:ss')}</span>
                  <span style={{width: '12%'}}>
                    <Popconfirm placement="right" title='确认删除该员工？' onConfirm={()=>this.removeStaff(index, item.task_id)} okText="确认" cancelText="取消">
                      <Button type="danger" style={{paddingRight: 25, paddingLeft: 25}}>删除</Button>
                    </Popconfirm>
                  </span>
                </section>
              </List.Item>
              )
            }
            footer={
              <Row gutter={8}>
                <Col span={5}>
                  <FormItem help="请选择部门">
                    <Select onChange={(e) => this.queryStaff(0, e)}>
                      {department.map(({department_id, department_name}) => <Option key={department_id}>{department_name}</Option>)}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={5}>
                  <FormItem help="请选择人员">
                    <Select onChange={(e) => this.queryStaff(1, e)}>
                      {staff.map(({staff_id, staff_name}) => <Option key={staff_id}>{staff_name}</Option>)}
                    </Select>
                  </FormItem>
                </Col>
                <Col span={11}>
                  <FormItem help="请选择项目参与人员的开始结束时间">
                    <RangePicker onChange={(e) => this.queryStaff(2, e)} />
                  </FormItem>
                </Col>
                <Col span={3}>
                  <FormItem>
                    <Popconfirm placement="right" title='新增后将发送一条短信给该员工' onConfirm={this.postStaff} okText="确认" cancelText="取消">
                      <Button type="primary" icon="plus-circle">
                        新增
                      </Button>
                    </Popconfirm>
                  </FormItem>
                </Col>
              </Row>
            }
          />
        }

        <List
          header='项目需求及文件'
          bordered
          dataSource={file}
          size="small"
          grid={{ gutter: 8, column: 6 }}
          className={styles.list}
          renderItem={(item, index) => (
            <List.Item style={{marginBottom: 0, padding: '0 0 8px 0'}}>
              <Popover 
                placement="right" 
                trigger="hover" 
                content={
                  <div>
                    <section style={{color: '#ccc', marginBottom: 8}}>{item.name}</section>
                    <section style={{ marginBottom: 10 }}>
                      <a href={item.url} download={item.name} target="_blank">下载</a>
                    </section>
                    <section style={{ marginBottom: 10 }}>
                      <Upload uploadFile={(_file) => this.changeFile(index, _file)}>
                        <a>替换</a>
                      </Upload>
                    </section>
                    <section style={{ marginBottom: 10 }} onClick={() => this.deleteFile(index)}>
                      <a>删除</a>
                    </section>
                  </div>
                }
              >
                <figure className={styles.gallery}> 
                  <section className={styles.image} style={{backgroundImage: `url(${item.url})`}} />                  
                  <figcaption>{item.name}</figcaption> 
                </figure>
              </Popover>
            </List.Item>
          )}
          footer={
            <div style={{textAlign: 'right'}}>
              <Upload uploadFile={this.uploadFile}>
                <Button type="primary" icon="upload">
                  上传
                </Button>
              </Upload>
            </div>
          }
        />
        
        <section style={{ width: 200, margin: 'auto', textAlign: 'center' }}>
          <Button type="primary" htmlType="submit" size="large" block>
            确认
          </Button>
        </section>
      </Form>
    )
  }
}

const WrappedTimeRelatedForm = Form.create()(TimeRelatedForm)

export default WrappedTimeRelatedForm